package com.azzcs.juc.cyclicbarrier;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wzg
 * @Date: 2021/6/17 上午11:25
 */
public class Main {
    private static Random random = new Random();
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(5,()->{
            System.out.println("run end...");
        });
        for (int i = 1; i < 6; i++) {
            new Thread(()->{

                try {
                    System.out.println(Thread.currentThread().getName()+"is run1...");
                    TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
                    System.out.println(Thread.currentThread().getName()+"is run2...");
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"is end...");
            },"thread"+i).start();
        }

        System.out.println("main run...");
    }
}
